<template>
  <view class="k-line-wrapper">
    <view class="kline-tabs-wrap bg-theme">
      <view
        class="kline-tab-item"
        v-for="(item, index) in tabList"
        :key="index"
        :data-current="index"
        :data-value="item.value"
        :data-period="item.value"
        :data-type="item.chartType"
        :data-key="item.type"
        @click="changePeriod"
        :class="{ active: index == tabCurrent }"
      >
        <!--         @click="lightChart.onPeriodChange" -->
        <view class="kline-tab-label">
          {{ item.name }}
        </view>
      </view>
      <view class="kline-tabs-fixed-wrpas">
        <view class="kline-tab-item has-sub" @click.stop="showMore">
          <view class="kline-tab-label">
            <span class="label" :class="{ active: subCurrentItem.name }">
              {{ subCurrentItem.name || $t("optionKline.labels[0]") }}
            </span>
            <u-icon
              class="arrow"
              name="arrow-down-fill"
              :size="arrowSize"
            ></u-icon>
          </view>

          <view class="kline-tab-more-wrap shadow bg-theme" v-if="isMoreShow">
            <view
              class="kline-tab-more-item"
              hover-class="kline-tab-more-item-hover"
              hover-stay-time="50"
              v-for="(moreItem, moreIndex) in subItem"
              :data-value="moreItem.value"
              :data-current="moreIndex"
              :data-period="moreItem.value"
              :data-type="moreItem.chartType"
              :data-key="moreItem.type"
              :data-isMore="true"
              :class="{ active: moreIndex === subMoreCurrent }"
              @click="changePeriod"
              :key="moreIndex"
            >
              <span class="kline-more-label">{{ moreItem.name }}</span>
            </view>
          </view>
        </view>
        <view class="kline-tab-item has-sub" @click="showIndex">
          <view class="kline-tab-label">
            <span class="label">{{ $t("optionKline.default[0]") }}</span>
            <u-icon
              class="arrow"
              name="arrow-down-fill"
              :size="arrowSize"
            ></u-icon>
          </view>

          <view class="kline-tab-index-wrap shadow bg-theme" v-if="isIndexShow">
            <view class="kline-tab-index-item">
              <view class="kline-index-label">{{
                $t("optionKline.default[5]")
              }}</view>
              <view class="kline-index-main">
                <view
                  class="kline-index-text"
                  hover-class="hover"
                  :class="{ active: subActive == 0 }"
                  :data-current="0"
                  :data-subactive="subActive"
                  data-type="MA"
                  @click.stop="klinecharts.setIndicator"
                  hover-stay-time="50"
                >
                  MA
                </view>
                <view
                  class="kline-index-text"
                  hover-class="hover"
                  :class="{ active: subActive == 1 }"
                  :data-current="1"
                  :data-subactive="subActive"
                  data-type="BOLL"
                  @click.stop="klinecharts.setIndicator"
                  hover-stay-time="50"
                >
                  BOLL
                </view>
              </view>
              <view
                class="kline-index-eye-wrap"
                :data-subactive="subActive"
                :class="{ brand: isSubActive }"
                :data-types="['BOLL', 'MA']"
                @click.stop="klinecharts.clearIndicator"
              >
                <u-icon
                  name="eye-fill"
                  :color="subActive !== null ? 'var(--brand-color)' : '#c3c3cd'"
                  size="40"
                ></u-icon>
              </view>
            </view>
          </view>
        </view>
        <!-- END OF SUB -->
        <view
          v-if="isDepth"
          class="kline-tab-item"
          :class="{ active: showDepth }"
          @click="switchToDepth"
        >
          {{ $t("tradeDepth.default") }}
        </view>
      </view>
    </view>
    <view
      class="k-line-content"
      id="k-line-chart"
      :prop="options"
      :change:prop="klinecharts.updateData"
      v-show="!showDepth"
    >
    </view>
    <view class="k-line-content" v-if="showDepth && isDepth">
      <view
        style="position: absolute; left: 0; top: 0; height: 100%; width: 100%"
      >
        <trade-depth-chart
          style="height: 100%"
          :list="depthList"
        ></trade-depth-chart>
      </view>
    </view>
  </view>
</template>

<script module="klinecharts" lang="renderjs">
import { init } from 'klinecharts'
let chart = null;

function getOptions() {
  // var axisLineColor = theme === 'dark' ? "#f3f3f3"
  var textColor = '#C8C8C8';
  var axisLineColor = '#333333';
  var gridColor =  '#EBEBEB'
  var crossTextBackgroundColor = '#373a40'
  var crossLineColor= axisLineColor
  return {
      precision: 6,
      grid: {
          horizontal: {
              color: gridColor
          },
          vertical: {
              color: gridColor
          }
      },
      candle: {
        type: 'candle_solid',
        priceMark: {
          high: {
            color: textColor
          },
          low: {
            color: textColor
          }
        },
        tooltip: {
          showRule: false,
          text: {
            color: textColor
          }
        },
        // 面积图
        area: {
          lineSize: 1,
          lineColor: '#0665e3',
          value: 'close',
          backgroundColor: [{
            offset: 0,
            color: 'rgba(33, 150, 243, 0.01)'
          }, {
            offset: 1,
            color: 'rgba(33, 150, 243, 0.2)'
          }]
        },
      },
      technicalIndicator: {
        tooltip: {
          showName: false,
          showParams: false,
          text: {
            size: 10,
            color: textColor
          }
        }
      },
      // 图表之间的分割线
      separator: {
        size: 0,
        color: axisLineColor,
      },
      xAxis: {
        show: true,
        axisLine: {
          show: false,
        },
        tickLine: {
          show: false,
        },
        tickText: {
          show: true,
          size: 12,
          family: 'DIN-Medium',
          color: textColor
        }
      },
      yAxis: {
        inside: true,
        axisLine: {
          show: false,
          color: axisLineColor
        },
        tickLine: {
          show: false,
          color: axisLineColor
        },
        tickText: {
          show: true,
          color: textColor,
          family: 'DIN-Medium',
          size: 12,
        },
      },
      crosshair: {
        horizontal: {
          line: {
            color: crossLineColor
          },
          text: {
            backgroundColor: crossTextBackgroundColor
          }
        },
        vertical: {
          line: {
            color: crossLineColor
          },
          text: {
            backgroundColor: crossTextBackgroundColor
          }
        }
      }
  }
}

export default {
  data() {
    return {
      paneId: 'subPanel',
      initIndicator: false,
    }
  },
  mounted() {
    this.initchart()
  },
  methods: {
    initchart() {
      chart = init('k-line-chart')
      chart.setPriceVolumePrecision(4, 6);
      chart.setStyleOptions(getOptions())
			chart.overrideTechnicalIndicator({
				name: 'MA',
				calcParams: [5, 10, 30]
			})
      this.setSubTechnicalIndicator('VOL')
    },
    updateData(newValue, oldValue, ownerInstance, instance) {
      switch (Number(newValue.type)) {
        case 1: {
          chart.applyNewData(newValue.data)
          this.setKlineChartType(newValue.chartType)
          if (!this.initIndicator && newValue.indicator) {
            this.setCandleTechnicalIndicator(newValue.indicator)
          }
          break
        }
        case 2:
          chart.updateData(newValue.data)
          break
        // case 3:
        //   this.setKlineChartType(newValue.chartType)
        //   break
      }
    },
    setCandleTechnicalIndicator(type) {
      chart.createTechnicalIndicator(type, false, { id: 'candle_pane' })
    },
    setSubTechnicalIndicator(type) {
      chart.createTechnicalIndicator(type, false, { height: 120, dragEnabled: false, id: this.paneId })
    },
    clearIndicator(e, ownerInstance) {
      chart.removeTechnicalIndicator('candle_pane')
      ownerInstance.callMethod('changeIndicatorByIndex', null)
    },
    setIndicator(e, ownerInstance) {
      const indicatorType = e.currentTarget.dataset.type;
      const current = e.currentTarget.dataset.current;
      this.setCandleTechnicalIndicator(indicatorType)
      ownerInstance.callMethod('changeIndicatorByIndex', current)
    },
    /**
     * @param {Object} type 可选参数{1，2}，其中1表示实心K线，2表示面积图
     */
    setKlineChartType(type) {
      if (!type) return;
      const chartType = type == 1 ? "candle_solid" : "area"
      chart.setStyleOptions({
        candle: { type: chartType }
      })
    }
  },
}
</script>

<script>
import Event from "@/static/tradingView/event.js";
import TradeDepthChart from "@/components/TradeDepthChart/TradeDepthChart";

export default {
  components: { TradeDepthChart },
  props: {
    symbol: {
      type: String,
      required: true,
    },
    match_id: {
      type: [Number, String],
      required: true,
    },
    isDepth: {
      type: Boolean,
      default: true,
    },
    depthList: {
      type: Array,
      default: () => [],
    },
    defaultIndicator: {
      type: [Number, String],
      default: 0,
    },
    activePeriod: {
      type: String,
      default: "1m",
    },
  },
  data() {
    return {
      arrowSize: "20",
      period: "1min",
      options: {
        type: undefined,
        series: [],
      },
      // 历史数据是否准备妥当
      ready: false,
      tabCurrent: 0,
      subMoreCurrent: undefined, // 更多面板列表索引
      isMoreShow: false,
      isIndexShow: false,
      showDepth: false,
      subList: [
        {
          text: "MA",
        },
        {
          text: "BOLL",
        },
      ],
      subActive: 0,
    };
  },
  computed: {
    activeIndicator() {
      return this.subList[this.subActive]?.text;
    },
    isSubActive() {
      /**
       * don't touch this code, `null` can be equall to 0
       * null == 0 ?  output: false
       * null > 0 ?   output: false
       * is null >= 0 also output false ?
       * no, the output is `true`
       */
      if (this.subActive == 0 || this.subActive > 0) {
        return true;
      }
      return false;
    },
    subItem() {
      return [
        {
          value: "30",
          type: "30min",
          name: this.$t("optionKline.default[2]").replace("{time}", 30),
          id: 3,
          period: "30m",
          chartType: 1,
        },
        {
          name: this.$t("optionKline.default[6]", { time: 1 }),
          type: "1week",
          value: "1W",
          period: "1W",
          chartType: 1,
        },
        {
          name: this.$t("optionKline.default[7]", { time: 1 }),
          value: "1M",
          type: "1mon",
          period: "1M",
          chartType: 1,
        },
      ];
    },
    subCurrentItem() {
      if (this.subMoreCurrent > -1) {
        return this.subItem[this.subMoreCurrent];
      }
      return {};
    },
    wssData() {
    },
    tabList() {
      return [
        {
          name: this.$t("optionKline.default[1]"),
          id: 0,
          type: "1min",
          period: "1",
          value: "1",
          chartType: 2,
        },
        {
          name: this.$t("optionKline.default[2]", { time: 1 }),
          id: 1,
          type: "1min",
          value: "1",
          period: "1m",
          chartType: 1,
        },
        {
          value: "5",
          name: this.$t("optionKline.default[2]").replace("{time}", 5),
          id: 2,
          type: "5min",
          period: "5m",
          chartType: 1,
        },
        {
          value: "60",
          type: "60min",
          name: this.$t("optionKline.default[3]").replace("{time}", 1),
          id: 4,
          chartType: 1,
          period: "1hour",
        },
        {
          value: "1D",
          type: "1day",
          name: this.$t("optionKline.default[4]").replace("{time}", 1),
          id: 5,
          period: "1D",
          chartType: 1,
        },
      ];
    },
    activeItem() {
      if (this.tabCurrent > -1) {
        return this.tabList[this.tabCurrent];
      }
      return this.subCurrentItem;
    },
  },
  watch: {
    wssData(newValue) {
      this.updateKlineData(newValue);
    },
  },
  mounted() {
    this.subActive = Number(this.defaultIndicator);
    this.tabCurrent = undefined;
    this.subMoreCurrent = undefined;
    const mainTabIndex = this.tabList.findIndex(
      (item) => item.period === this.activePeriod
    );
    if (mainTabIndex > -1) {
      this.tabCurrent = mainTabIndex;
    }
    if (!mainTabIndex) {
      const index = this.subItem.findIndex(
        (item) => item.period === this.activePeriod
      );
      if (index > -1) {
        this.subMoreCurrent = index;
      }
    }
    this.fetchHistory();
  },
  methods: {
    switchToDepth() {
      this.tabCurrent = undefined;
      this.period = undefined;
      this.subMoreCurrent = undefined;

      this.showDepth = true;
    },
    changeIndicatorByIndex(index) {
      this.subActive = index;
    },
    changePeriod(e) {
      console.log("PERIOD => ", e);
      const isMore = e.currentTarget.dataset?.ismore;
      const index = e.currentTarget.dataset.current;
      const key = e.currentTarget.dataset.key;
      this.showDepth = false;
      if (isMore) {
        this.tabCurrent = undefined;
        this.subMoreCurrent = index;
        this.period = key;
      } else {
        this.subMoreCurrent = undefined;
        this.tabCurrent = index;
        this.period = key;
      }
      this.fetchHistory();
    },
    showIndex() {
      this.showDepth = false;
      this.isMoreShow = false;
      this.isIndexShow = !this.isIndexShow;
    },
    showMore() {
      this.showDepth = false;
      this.isIndexShow = false;
      this.isMoreShow = !this.isMoreShow;
    },
    async fetchHistory() {
      const params = {
        symbol: this.symbol,
        period: this.period,
        currency_match_id: this.match_id,
      };

      const res = await this.$u.get("/market/kline", params);
      if (res.code === 1) {
        let series = res.data.map((item) => {
          item.open = Number(item.open);
          item.close = Number(item.close);
          item.high = Number(item.high);
          item.low = Number(item.low);
          item.volume = Number(item.volume);
          item.timestamp = Number(item.time);
          return item;
        });
        this.setChartOptions(1, series);
        let [lastData] = res.data.reverse();
        Event.emit("close", { type: this.period, close: lastData.close });
        this.ready = true;
      }
    },
    updateKlineData(item) {
      if (!this.ready) return;
      if (item.type === "KLINE" && this.period === item?.kline?.period) {
        const params = {
          type: 2,
          data: {
            open: +item.kline?.open,
            close: +item.kline?.close,
            high: +item.kline?.high,
            low: +item.kline?.low,
            volume: +item.kline?.volume,
            timestamp: +item.kline?.time,
          },
        };
        Event.emit("close", { type: this.period, close: item.kline?.close });
        this.setChartOptions(params.type, params.data);
      }
    },
    setChartOptions(type, data) {
      this.options = {
        type,
        data,
        chartType: this.activeItem.chartType,
        indicator: this.activeIndicator,
      };
    },
  },
};
</script>

<style lang="less" scoped>
.k-line-wrapper {
  height: 100%;
  display: flex;
  flex-direction: column;
  .k-line-content {
    flex-basis: 0;
    flex-grow: 1;
    position: relative;
  }
}

.kline-tabs-wrap {
  flex-basis: 0;
  flex-shrink: 0;
  font-size: 24rpx;
  display: flex;
  flex-flow: row nowrap;
  align-items: center;
  justify-content: space-between;
  padding: 0 30rpx;
  background: white;
  color: #C8C8C8;
  font-family: DIN-Regular-2;
  // font-weight: bold;
  position: relative;
  z-index: 101;
  border-bottom: 1px solid #EBEBEB;
  .kline-tab-item {
    height: 66rpx;
    line-height: 66rpx;
    text-align: center;
    &.has-sub {
      margin-right: 20rpx;
    }
    &:last-child {
      margin-right: 0;
    }
    &.active {
      // color: var(--brand-color);
      color: #000000;
      border-bottom: 1px solid var(--brand-color);
    }
    .kline-tab-label {
      .label {
        &.active {
          color: @brand-color;
        }
      }
    }
  }

  .kline-tabs-fixed-wrpas {
    display: flex;
    .kline-tab-item {
    }
    .arrow {
      transform: scale(0.63);
      margin-left: 8rpx;
    }
  }
  .kline-tab-more-wrap {
    z-index: 110;
    display: flex;
    flex-flow: row wrap;
    background-color: @white;
    position: absolute;
    left: 10rpx;
    right: 10rpx;
    bottom: 0rpx;
    transform: translateY(100%);
    padding: 10rpx;
    .kline-tab-more-item {
      width: 120rpx;
      &.active {
        color: var(--brand-color);
      }
      &.kline-tab-more-item-hover {
        background-color: @bg-color-gray;
      }
    }
  }

  .kline-tab-index-wrap {
    position: absolute;
    left: 10rpx;
    right: 10rpx;
    bottom: -10rpx;
    transform: translateY(100%);
    padding: 10rpx;
    background-color: @white;
    padding: 0 30rpx;
    .kline-tab-index-item {
      display: flex;
      justify-content: space-between;
      .kline-index-label {
        flex: 0 0 auto;
        width: 200rpx;
      }
      .kline-index-main {
        flex: 1;
        display: flex;
        flex-flow: row wrap;
        .kline-index-text {
          width: 100rpx;
          &.active {
            color: @brand-color;
          }
        }
      }
      .kline-index-eye-wrap {
        flex: 0 0 auto;
        width: 200rpx;
        font-size: 30rpx;
      }
    }
  }
}
</style>
